import { showSection } from './utils.js';

// 检查登录状态
export function checkAuth() {
    const token = localStorage.getItem('access_token');
    if (!token) {
        window.location.href = '/login';
        return false;
    }
    return true;
}

// 获取当前用户信息
export async function fetchCurrentUser() {
    try {
        const response = await fetch('/api/current_user', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const data = await response.json();
            document.getElementById('username-display').textContent = data.username;
            document.getElementById('user-avatar').src = `https://ui-avatars.com/api/?name=${encodeURIComponent(data.username)}&background=2563eb&color=fff`;

            // 如果不是管理员，隐藏管理相关功能
            if (!data.is_admin) {
                document.querySelector('a[href="#users"]').style.display = 'none';
                document.querySelector('a[href="#models"]').style.display = 'none';
                document.querySelector('a[href="#documents"]').style.display = 'none';
            }
        } else {
            throw new Error('获取用户信息失败');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('获取用户信息失败，请重新登录');
        logout();
    }
}

// 登出
export async function logout() {
    try {
        await fetch('/api/logout', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
    } catch (error) {
        console.error('登出错误:', error);
    } finally {
        localStorage.removeItem('access_token');
        localStorage.removeItem('user_data');
        window.location.href = '/login';
    }
}

// 初始化认证相关事件
export function initAuthEvents() {
    // 登出按钮事件
    document.getElementById('logout-btn').addEventListener('click', logout);

    // 导航菜单点击事件
    document.querySelectorAll('nav a').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const target = this.getAttribute('href').substring(1);
            showSection(target);
        });
    });
}